import 'package:boss/main.dart';
import 'package:boss/models/commodity.dart';
import 'package:boss/provider/commodity_provider.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/page/costManagement/eventBus/event_bus.dart';
import 'package:boss/ui/page/costManagement/widget/cost_management_list.dart';
import 'package:boss/ui/widget/form/base_text_form_field.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hi_common/hi_common.dart';
import 'package:provider/provider.dart';

class CostManagementBatchList extends StatefulWidget {
  final dynamic commodityProvider;

  const CostManagementBatchList({Key key, this.commodityProvider}) : super(key: key);

  @override
  _State createState() => _State();
}

class _State extends State<CostManagementBatchList> {
  //记录拆分的多规格菜品sku信息
  List<MultipleSku> multipleSkuArr = [];

  List<Commodity> get storeMenusArr {
    List<Commodity> newArr = [];
    multipleSkuArr = [];
    widget.commodityProvider.storeMenus.forEach((str) {
      if (str.commodityList.length != 0) {
        str.commodityList.forEach((item) {
          if (item.commoditySkuList.length == 0) {
            newArr.add(item);
            multipleSkuArr.add(null);
          } else {
            item.commoditySkuList.forEach((str) {
              newArr.add(item);
              multipleSkuArr.add(MultipleSku(skuId: str.skuId, skuName: str.skuName, price: str.skuPrice, skuCostPrice: str.skuCostPrice));
            });
          }
        });
      }
    });

    return newArr ?? [];
  }

  List<TextEditingController> textControllerArr = [];

  var _subscription;

  @override
  void initState() {
    // TODO: implement initState

    super.initState();

    Future.delayed(Duration(milliseconds: 0), () async {
      _subscription = costEventBus.on<BatchSub>().listen((event) {
        if (event.data != null) {
          subBatchCost();
        }
      });
    });

    for (var i = 0; i < (storeMenusArr ?? []).length; i++) {
      textControllerArr.add(TextEditingController());
      textControllerArr[i].text = (multipleSkuArr[i] == null
          ? (storeMenusArr[i].costPrice == -1 ? '' : (AmountUtil.price2String((storeMenusArr[i].costPrice) ?? 0)))
          : (multipleSkuArr[i].skuCostPrice == -1 ? '' : ((AmountUtil.price2String((multipleSkuArr[i].skuCostPrice) ?? 0)))));
    }

    setState(() {});
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _subscription.cancel();
    textControllerArr.map((str) => str.dispose());
    super.dispose();
  }

  subBatchCost() async {
    List<dynamic> batchArr = [];

    for (var z = 0; z < textControllerArr.length; z++) {
      if (textControllerArr[z].text != '' && textControllerArr[z].text != null) {
        batchArr.add({
          "commodityId": storeMenusArr[z].id,
          "costPrice": ((num.parse(textControllerArr[z].text)) * 100).toInt() ?? 0,
          "skuId": multipleSkuArr[z] == null ? 0 : multipleSkuArr[z].skuId,
        });
      }
    }

    try {
      showLoadingToast();
      var res = await api.batchSetCostPrice({'listCommodityCostPriceDetail': batchArr});
      if (res.successful()) {
        toast("批量成本价设置成功!");

        try {
          showLoadingToast();
          var commodityProvider = Provider.of<CommodityProvider>(
            context,
            listen: false,
          );
          await commodityProvider?.initData();
        } catch (e) {} finally {
          hideLoadingToast();
          Navigator.pop(context);
        }
      } else {
        toast(res.msg);
      }
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: ListView.builder(
        padding: EdgeInsets.symmetric(
          vertical: 30.w,
          horizontal: 30.w,
        ),
        itemBuilder: (context, index) {
//          return CostManagementBatchItem(index:index,storeMenusArr:storeMenusArr,multipleSkuArr:multipleSkuArr,);
          return Container(
            child: Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Expanded(
                      child: BaseTextFormField(
                        controller: textControllerArr[index],
                        prefixText:
                            '${storeMenusArr[index]?.title ?? '--'}${multipleSkuArr[index] == null ? '' : '(' + multipleSkuArr[index]?.skuName + ')' ?? ''} ${(' 售价:￥${AmountUtil.price2String((storeMenusArr[index]?.price) ?? 0)}')}',
                        hintText: '输入菜品成本价格',
                        keyboardType: TextInputType.numberWithOptions(decimal: true),
                        inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
                        onChanged: (e) {
//                          print("________test");
//                          print(textControllerArr);
                        },
                      ),
                    ),
                    Text(
                      "元",
                      style: TextStyleConstant().normal_1_26,
                    ),
                  ],
                ),
              ],
            ),
          );
        },
        itemCount: storeMenusArr.length,
      ),
    );
  }
}
